package com.waverider.promotion.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.iacrqq.util.DateUtil;

/**
 * 
 * @author sihai
 * 
 */
public abstract class AbstractController implements Controller {
	protected static final String OPERATION_KEY = "_operation_";
	protected static final String LOGIN_CONTEXT = "_login_context_";
	protected static final String ACTION_METHOD = "_method_";

	protected static final String ERROR_MSG = "errorMsg";
	protected static final String SUCCEED_MSG = "succeedMsg";

	protected static final String NOT_LOGIN_ERROR_MSG = "请从淘宝开放平台登录！！！";
	protected static final String UNKNOWN_OPERATION_ERROR_MSG = "未知操作！！！";

	protected static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
	protected static final String DEFAULT_DATE_FORMAT_1 = "yyyy-MM-dd";

	protected static final String JSON_SUCCEED_KEY = "succeed";
	protected static final String JSON_ERROR_MSG_KEY = ERROR_MSG;

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		//
		ModelAndView mv = handle(request, response);

		if (mv != null) {
			Map<String, Object> context = mv.getModel();
			context.put("dateUtil", new DateUtil());
		}

		// 后置处理
		return mv;
	}

	//
	protected abstract ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response) throws Exception;

	protected boolean isLogined(HttpSession session) {
		LoginContext loginContext = (LoginContext) session
				.getAttribute(LOGIN_CONTEXT);
		if (loginContext == null) {
			return false;
		}

		return loginContext.getIsLogin();
	}

	protected Long getUserId(HttpSession session) {
		LoginContext loginContext = (LoginContext) session
				.getAttribute(LOGIN_CONTEXT);
		return loginContext.getVistorId();
	}

	protected Long getShopId(HttpSession session) {
		LoginContext loginContext = (LoginContext) session
				.getAttribute(LOGIN_CONTEXT);
		return loginContext.getShopId();
	}

	protected String getUserNick(HttpSession session) {
		LoginContext loginContext = (LoginContext) session
				.getAttribute(LOGIN_CONTEXT);
		return loginContext.getVistorNick();
	}

	protected String getSessionKey(HttpSession session) {
		LoginContext loginContext = (LoginContext) session
				.getAttribute(LOGIN_CONTEXT);
		return loginContext.getSessionKey();
	}

	protected boolean getUnfree(HttpSession session) {
		LoginContext loginContext = (LoginContext) session
				.getAttribute(LOGIN_CONTEXT);
		return loginContext.getUnfree();
	}
}
